<template>
  <base-modal :show.sync="visible" :title="title" width="700px">
    <div class="pad-20 add-user-model">
      <el-form
        label-position="top"
        
        ref="engineerAddForm"
        :model="fieldValue"
        :rules="rules"
      >
        <el-form-item :label="$t('common.base.addEngineer')" prop="user" required>
          <biz-remote-select
            class="main-dispatcher-user"
            v-model="fieldValue.user"
            multiple
            :multiple-limit="10"
            cleared
            :remote-method="remoteUser"
            :placeholder="$t('common.base.pleaseSelect')"
            :computed-width-keys="['name']"
          >
            <div
              class="engineer-template-option"
              slot="option"
              slot-scope="{ option }"
            >
              <img class="user-icon" :src="head(option.head)" />
              <span class="user-name">{{ option.displayName }}</span>
            </div>
          </biz-remote-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.belongProvieder')" prop="provider" required>
          <biz-remote-select
            class="main-dispatcher-user"
            v-model="fieldValue.provider"
            cleared
            :inputDisabled="isProviderUser"
            :remote-method="fetchProvider"
            :placeholder="$t('common.base.pleaseSelect')"
            :computed-width-keys="['providerName']"
          ></biz-remote-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.role')" prop="role" required>
          <biz-remote-select
            v-model="fieldValue.role"
            cleared
            :remote-method="fetchRole"
            :placeholder="$t('common.base.pleaseSelect')"
            :computed-width-keys="['name']"
          >
            <div
              class="customer-template-option"
              slot="option"
              slot-scope="{ option }"
            >
              <span>{{ option.name }}</span>
            </div>
          </biz-remote-select>
        </el-form-item>
      </el-form>
      <div class="role-txt-box">
        {{$t('serviceProvider.addProviederSelectRole')}}
      </div>
      <div class="tips">
        {{$t('common.base.optCriterion[0]')}}<br />
        {{$t('common.base.optCriterion[1]')}}<br />
        {{$t('common.base.optCriterion[2]')}}<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{$t('common.base.optCriterion[3]')}}<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{$t('common.base.optCriterion[4]')}}<br />
        {{$t('common.base.optCriterion[5]')}}<br />
        {{$t('common.base.optCriterion[6]')}}<br />
        <el-checkbox v-model="isNotice">
          {{$t('common.base.optCriterion[7]')}}
        </el-checkbox>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="plain-third" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="validate" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import {
  bindsUser,
  getProviderDropDownList,
  getEngineerRole,
  getUserList,
} from '@src/api/serviceProviderApi';
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import * as serviceProviderApi from '@src/api/serviceProviderApi';
import { getRootWindowInitData } from "@src/util/window";
export default {
  name: 'AddUser',

  data() {
    return {
      title: this.$t('common.base.addEngineer'),
      visible: false,
      fieldValue: {},
      loading: false,
      isNotice: false,
      pending: false,
      rules: {
        user: [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: this.$t('common.placeholder.selectEngineer'),
          },
        ],
        provider: [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: this.$t('common.placeholder.selectServiceProvider'),
          },
        ],
        role: [
          {
            required: true,
            trigger: ['blur', 'change'],
            message: this.$t('common.placeholder.selectRole'),
          },
        ],
      },
    };
  },

  computed: {
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
  },
  methods: {
    async openDialog(value) {
      this.$refs['engineerAddForm'].resetFields();
      this.isNotice = false;
      this.fieldValue = {
        user: [],
        provider: [],
        role: []
      };
      if (value && Object.keys(value).length) {
        this.fieldValue.provider = [value];
      }
      this.visible = true;
    },

    /* 查询角色*/
    async fetchRole(params = {}) {
      if (!this.fieldValue?.provider?.length) {
        // 如果服务商是空的话
        return this.$message({
          type: 'warning',
          message: this.$t('common.placeholder.selectProvieder'),
        });
      }
      let providerId = this.fieldValue?.provider?.[0]?.value;
      try {
        let { keyword } = params;
        const dataToSend = {
          roleName: keyword,
          providerId,
        };
        let res = await serviceProviderApi.getEngineerRole(dataToSend);
        if (!res?.data) return;
        let data = {
          // 目前角色没有分页，做成假的分页，以后接口修改直接修改这里
          total: res.data.length,
          hasNextPage: false,
        };
        data.list = res.data.map(item => {
          return {
            label: (item && item.name) || '',
            value: (item && item.id.toString()) || '',
            id: (item && item.id.toString()) || '',
            name: (item && item.name) || '',
          };
        });
        return data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },

    /************人员****************/
    async remoteUser(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageSize,
          pageNum,
          roleId: '',
          roleType: 'noauth',
          enabled: '',
        };
        let res = await getUserList(dataToSend);
        if (!res?.data?.list) return;
        res.data.list.forEach(item => {
          item.label = (item && item.displayName) || '';
          item.value = (item && item.userId) || '';
        });
        return res.data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /************人员****************/
    /*查询所属服务商*/
    async fetchProvider(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        let res = await getProviderDropDownList(dataToSend);
        if (!res?.result) return;
        this.handleTagData(res.result.list || []);
        return res.result;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    handleTagData(list) {
      list.forEach(item => {
        item.label = (item && item.providerName) || '';
        item.value = (item && item.tenantProviderId) || '';
      });
    },
    async validate() {
      this.$refs.engineerAddForm.validate(vaild => {
        if (vaild) {
          if (!this.isNotice) {
            this.$message.warning({
              message: this.$t('common.placeholder.readExplainAndAgree'),
            });
          } else {
            this.submit();
          }
        }
      });
    },
    async submit() {
      try {
        this.pending = true;
        this.visible = false;
        let data = {
          roleId: this.fieldValue?.role?.[0]?.id,
        };
        if (this.fieldValue?.provider && this.fieldValue.provider.length) {
          data.tenantProviderId = this.fieldValue.provider[0].value;
        }
        if (this.fieldValue?.user && this.fieldValue.user.length) {
          data.userIds = this.fieldValue.user.map(item => {
            return item.userId;
          });
        }
        let res = await bindsUser(data);
        this.$notify({
          type: res.success ? 'success' : 'error',
          title: res.success ? this.$t('common.base.tip.addSuccess') : (res?.message || this.$t('common.base.addFailed')),
        });
        // 刷新表格
        this.$emit('refresh');
      } catch (e) {
        console.error(e);
      } finally {
        this.pending = false;
      }
    },
    head(src) {
      if (!src) return defaultAvatar;
      return src;
    },
  },
};
</script>

<style scoped lang="scss">
.add-user-model {
  z-index: 300 !important;
  .tips {
    padding: 10px 0;
    color: $text-color-secondary;
    line-height: 24px;
  }
  .role-txt-box {
    padding: 5px 0 15px 100px;
    color: $text-color-secondary;
    border-bottom: 1px solid $border-color-base;
  }
  ::v-deep .el-select {
    width: 100%;
  }
}
</style>
<style lang="scss">
.engineer-template-option {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  .user-icon {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background-repeat: no-repeat;
  }
  .user-name {
    margin-left: 10px;
  }
}
</style>
